import time

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
# csrf
from django.views.decorators.csrf import csrf_exempt
# 授权,采用jwt进行配置,JWTencode(解密token)  加密部分放到setting里边全局调用 JWTdecode函数
from app_User.utils import JWTencode

# 权限,基础权限
from rest_framework.permissions import BasePermission
# 限流
from rest_framework.throttling import BaseThrottle

# 解释器
from rest_framework.parsers import BaseParser, FormParser, JSONParser

from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.utils import json

from rest_framework.views import APIView
from app_User import models
from django.core import serializers

from rest_framework import serializers

class StudentSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Students
        # fields = '__all__'
        desph = 1


# Create your views here.
def test(request):
    # 返回一个学生主页的信息,返回主页相关的数据,序列化成json返回
    pageid = 1  #传来的pageid



    # stdinfo = models.Students.objects.filter(id = pageid)
    stdinfo1 = models.Students.objects.all()

    stdSrc = StudentSerializer(instance=stdinfo1,many=True)
    print(type(stdinfo1))

    print(type(stdSrc.data))

    ret = json.dumps(stdSrc.data,ensure_ascii = False)
    print(type(ret))

    return HttpResponse(ret)

class Login(APIView):
    # http://127.0.0.1:8000/user/login/

    authentication_classes = []

    def get(self,request, *args, **kwargs):
        """
        get
            显示登录页
                render 展示登录页面
        """

        return render(request,'app_User/login.html', locals())

    @csrf_exempt
    def post(self,request):

        """
        post
            用户名密码登录获取token
                {"username":"xxx","password":"xxx"}
                 return token
        """

        ret = {'code': 1000, 'result': ''}
        # print(request.data)
        # print(request.content_type)
        # self.dispatch()
        username = request.data.get('username')  #针对ajax  #request.data是restful framework的获取的方式
        password = request.data.get('password') #针对ajax   #request.data是restful framework的获取的方式
        print(username,password)

        # 存进去token
        userObj = models.Students.objects.filter(username=username,password=password).first()
        if not userObj:
            raise exceptions.AuthenticationFailed("用户名或密码错误111")
        token = JWTencode.createToken({'user_id':userObj.id,'username':username},100)
        print(token)
        models.UserToken.objects.update_or_create(userToken_User =userObj, defaults={'token': token})
        return JsonResponse({"code":1000,"data":[token,userObj.id]},safe=False)

class index(APIView):
    '''http://127.0.0.1:8000/user/index/'''

    # get,根据token获取用户界面json数据
    # get  json  :token
    # return json  :userJsonData

    def get(self,request, *args, **kwargs):
        print('每个用户的对外展示页面')

        # 获取提交的json,提取pageid:
        json_str = request._request.body
        pageid = request.GET.get('pageid')
        token = request.auth
        print('------------主页 get方法 Start')
        print(request.data)
        print(request.content_type)
        print('token',token)
        print('访问id',pageid)
        print('------------主页 get方法 End')

        # 获取该pageid下用户信息
        accountInfo = models.Students.objects.filter(id=pageid).first()
        # 获取主用户的id
        stdid = request.user['user_id']
        ret = {
            'id':accountInfo.id,
            'code' :1000,
            'username':accountInfo.username,
            'realName':accountInfo.realName,
            'sex':accountInfo.sex,
            'sfz':accountInfo.sfz,
            'imgurl' :accountInfo.userhead,
               }

        #判断stdid和pageid是否一致,一致是个人主页,不一致是别人的主页

        if int(stdid) != int(pageid):
            #访问别人的主页
            print("正在访问别人的主页")
            comment_QuSet = None  # 不给看一些东西
        else:
            # 多里边查一,该用户下面评论内容获取
            comment_QuSet = models.Comment.objects.filter(commentToId_id__id=pageid).all()  #获取到的是QuerySet,需要序列化
            print('--------------------')
            for comment in comment_QuSet:
                print(comment.commentToId_id)
            print('--------------------')

        # return JsonResponse(ret, safe=False)
        return render(request,'app_User/index.html', locals())
        # 登录,需要password 需要token

    def post(self,request, *args, **kwargs):
        print('nihao ')
        return HttpResponse("调用了POST方法")




#评论系统
class Comment(APIView):
    #get,获取用户的评论数据
    def get(self,request, *args, **kwargs):
        print('GET comment 方法 ')
        return HttpResponse("调用了评论系统get方法,获取评论")

    # 进行评论,用户给别人评论
    def post(self,request, *args, **kwargs):
        print('POST comment 方法 ')
        return HttpResponse("调用了评论系统POST方法,添加评论")


from app_User.utils.serializers.pageSerialiser import pagesserializer
from rest_framework.response import Response   #用drf的Response可以直接输出序列化内容.data
from rest_framework.pagination import PageNumberPagination
from app_User.utils.pageFenYE.page_fenye import MyPagePaginations,MyPagePaginations1
class Page(APIView):
    authentication_classes = []
    def post(self,request, *args, **kwargs):
        ret = models.Roles.objects.all()
        # ser = pagesserializer(instance=ret,many=True)

        #定义分页

        pg = MyPagePaginations1()  #实例化分页
        pagerRole= pg.paginate_queryset(queryset=ret,request=request,view=self)
        ser = pagesserializer(instance=pagerRole,many=True)

        # print(pagerRole)
        # return Response(ser.data)
        return pg.get_paginated_response(ser.data)
